
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using MySql.Data.MySqlClient;
using AnovoAndes.Framework.Utilidades;
using NovaSystem.EntidadesNegocio;

namespace NovaSystem.AccesoDatos
{
	public class productoDAO 
	{
			
		#region [Variables Publicas]
        List<string> listaEsquema = new List<string>();
		System.Configuration.AppSettingsReader read = new System.Configuration.AppSettingsReader();
        #endregion
		
		#region Constructores
		public productoDAO()
		{
		}
		#endregion
		
		#region Metodos Privados
		
		 private List<string> LlenarEsquema(IDataReader dr)
        {
            DataTable schemaTable;
            schemaTable = dr.GetSchemaTable();
            listaEsquema = new List<string>();
            const int columnaNombre = 0;
            //Para cada campo de la tabla...
            foreach (DataRow myField in schemaTable.Rows)
            {
                //Agrega nombre del campo a la lista generica.
                listaEsquema.Add(myField[columnaNombre].ToString());
            }
            return listaEsquema;

        }
		
		private producto Crear(IDataReader dr)
		{
			producto vObj = new producto();
			try
			{
				listaEsquema.Sort();
							if (listaEsquema.BinarySearch("idProducto",StringComparer.OrdinalIgnoreCase)>-1)
				{
					if(!(dr["idProducto"] is System.DBNull))
					{
						vObj.idProducto= (int)dr["idProducto"];
					}
				}
				if (listaEsquema.BinarySearch("codigo",StringComparer.OrdinalIgnoreCase)>-1)
				{
					if(!(dr["codigo"] is System.DBNull))
					{
						vObj.codigo= (string)dr["codigo"];
					}
				}
				if (listaEsquema.BinarySearch("descripcion",StringComparer.OrdinalIgnoreCase)>-1)
				{
					if(!(dr["descripcion"] is System.DBNull))
					{
						vObj.descripcion= (string)dr["descripcion"];
					}
				}
				if (listaEsquema.BinarySearch("conceptoFamilia",StringComparer.OrdinalIgnoreCase)>-1)
				{
					if(!(dr["conceptoFamilia"] is System.DBNull))
					{
						vObj.conceptoFamilia= (string)dr["conceptoFamilia"];
					}
				}
				if (listaEsquema.BinarySearch("codigoFamilia",StringComparer.OrdinalIgnoreCase)>-1)
				{
					if(!(dr["codigoFamilia"] is System.DBNull))
					{
						vObj.codigoFamilia= (string)dr["codigoFamilia"];
					}
				}
				if (listaEsquema.BinarySearch("conceptoCategoria",StringComparer.OrdinalIgnoreCase)>-1)
				{
					if(!(dr["conceptoCategoria"] is System.DBNull))
					{
						vObj.conceptoCategoria= (string)dr["conceptoCategoria"];
					}
				}
				if (listaEsquema.BinarySearch("codigoCategoria",StringComparer.OrdinalIgnoreCase)>-1)
				{
					if(!(dr["codigoCategoria"] is System.DBNull))
					{
						vObj.codigoCategoria= (string)dr["codigoCategoria"];
					}
				}
                if (listaEsquema.BinarySearch("idBodega", StringComparer.OrdinalIgnoreCase) > -1)
                {
                    if (!(dr["idBodega"] is System.DBNull))
                    {
                        vObj.idBodega = (int)dr["idBodega"];
                    }
                }
                if (listaEsquema.BinarySearch("usuario", StringComparer.OrdinalIgnoreCase) > -1)
                {
                    if (!(dr["usuario"] is System.DBNull))
                    {
                        vObj.usuario = (string)dr["usuario"];
                    }
                }
                if (listaEsquema.BinarySearch("fechaRegistro", StringComparer.OrdinalIgnoreCase) > -1)
                {
                    if (!(dr["fechaRegistro"] is System.DBNull))
                    {
                        vObj.fechaRegistro = (DateTime)dr["fechaRegistro"];
                    }
                }

				return vObj;
			}
			catch(Exception ex)
			{
				throw new Exception(ex.Message);
			}
		}
		
		private List<producto> CrearDTOs(IDataReader dr) 
		{
			List<producto> listaDTO = new List<producto>();
			if 	(dr != null)
			{
				listaEsquema = LlenarEsquema(dr);// Validadores.LlenarEsquema(dr);
				
				while (dr.Read())
				{
					listaDTO.Add(Crear(dr));
				}
				dr.Close();
			}
			return listaDTO;
		}
		
		#endregion
		
		#region Metodos Publicos
        public producto BuscarProductoCodigo(string codigo)
        {
            MySqlConnection conn = new MySqlConnection();
            List<producto> lista = new List<producto>();
            try
            {
                string connString = read.GetValue("Database", typeof(string)).ToString();
                conn.ConnectionString = connString;
                conn.Open();
                MySqlCommand objDbCommand = new MySqlCommand();
                objDbCommand.Connection = conn;
                objDbCommand.CommandType = CommandType.StoredProcedure;
                objDbCommand.CommandText = "usp_buscaProductoCodigo";
                objDbCommand.Parameters.AddWithValue("_codigo", codigo);
                using (IDataReader objDataReader = objDbCommand.ExecuteReader())
                {
                    lista = CrearDTOs(objDataReader);
                }
                CerrarConn(conn);
                if (lista.Count > 0)
                    return lista[0];
                else
                    return null;
            }
            catch (Exception ex)
            {
                CerrarConn(conn);
                throw new Exception(ex.Message);
            }
        }

            


        public List<producto> BuscarProducto(producto dto)
        {
            MySqlConnection conn = new MySqlConnection();
            List<producto> lista = new List<producto>();
            try
            {
                string connString = read.GetValue("Database", typeof(string)).ToString();
                conn.ConnectionString = connString;
                conn.Open();
                MySqlCommand objDbCommand = new MySqlCommand();
                objDbCommand.Connection = conn;
                objDbCommand.CommandType = CommandType.StoredProcedure;
                objDbCommand.CommandText = "usp_S_buscaProducto";
                objDbCommand.Parameters.AddWithValue("_codigo", AssertNull.getValue(dto.codigo));
                objDbCommand.Parameters.AddWithValue("_descripcion", AssertNull.getValue(dto.descripcion));
                objDbCommand.Parameters.AddWithValue("_codigoCategoria", AssertNull.getValue(dto.codigoCategoria));
                objDbCommand.Parameters.AddWithValue("_codigoFamilia", AssertNull.getValue(dto.codigoFamilia));
                using (IDataReader objDataReader = objDbCommand.ExecuteReader())
                {
                    lista = CrearDTOs(objDataReader);
                }
                CerrarConn(conn);
                return lista;
            }
            catch (Exception ex)
            {
                CerrarConn(conn);
                throw new Exception(ex.Message);
            }
        }


		public List<producto> Listar()
		{
			MySqlConnection conn = new MySqlConnection();
			List<producto> lista = new List<producto>();
			try
			{
				string connString = read.GetValue("Database",typeof(string)).ToString();
				conn.ConnectionString = connString;
				conn.Open();
				MySqlCommand objDbCommand = new MySqlCommand();
				objDbCommand.Connection = conn;
				objDbCommand.CommandType = CommandType.StoredProcedure;
				objDbCommand.CommandText = "usp_s_producto";
				
				using (IDataReader objDataReader = objDbCommand.ExecuteReader())
				{
					lista = CrearDTOs(objDataReader);
				}
				CerrarConn(conn);
				return lista;
			}
			catch(Exception ex)
			{
				CerrarConn(conn);
				throw new Exception(ex.Message);
			}
		}
		
		
		private void CerrarConn(MySqlConnection conn)
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }
		
		public string Insertar( producto dto)
		{
			MySqlConnection conn = new MySqlConnection();
			try
			{
				string connString = read.GetValue("Database",typeof(string)).ToString();
				conn.ConnectionString = connString;
				conn.Open();
				MySqlCommand objDbCommand = new MySqlCommand();
				objDbCommand.Connection = conn;
				objDbCommand.CommandType = CommandType.StoredProcedure;
				objDbCommand.CommandText = "usp_I_producto";
				objDbCommand.Parameters.AddWithValue("_codigo",AssertNull.getValue(dto.codigo));
				objDbCommand.Parameters.AddWithValue("_descripcion",AssertNull.getValue(dto.descripcion));
				objDbCommand.Parameters.AddWithValue("_conceptoFamilia",AssertNull.getValue(dto.conceptoFamilia));
				objDbCommand.Parameters.AddWithValue("_codigoFamilia",AssertNull.getValue(dto.codigoFamilia));
				objDbCommand.Parameters.AddWithValue("_conceptoCategoria",AssertNull.getValue(dto.conceptoCategoria));
				objDbCommand.Parameters.AddWithValue("_codigoCategoria",AssertNull.getValue(dto.codigoCategoria));
                objDbCommand.Parameters.AddWithValue("_usuario", AssertNull.getValue(dto.usuario));
				objDbCommand.ExecuteNonQuery();
				CerrarConn(conn);
				return "";
			}
			catch(Exception ex)
			{
				CerrarConn(conn);
				throw new Exception(ex.Message);
			}
		}
		
		public void Eliminar(producto dto)
		{
			MySqlConnection conn = new MySqlConnection();
			try
			{
				string connString = read.GetValue("Database",typeof(string)).ToString();
				conn.ConnectionString = connString;
				conn.Open();
				MySqlCommand objDbCommand = new MySqlCommand();
				objDbCommand.Connection = conn;
				objDbCommand.CommandType = CommandType.StoredProcedure;
				objDbCommand.CommandText = "usp_D_producto";
								objDbCommand.Parameters.AddWithValue("_idProducto",AssertNull.getValue(dto.idProducto));

				objDbCommand.ExecuteNonQuery();
				CerrarConn(conn);
			}
			catch(Exception ex)
			{
				CerrarConn(conn);
				throw new Exception(ex.Message);
			}
		}
		
		#endregion
		
	}
}
